$(function() {
  if($("#thesidebar").length > 0 && window.location.href.indexOf('/admin/') < 0) {
    ajaxUpdateIndex();
  }
  
  if($("#refreshCode").length > 0) {
    $("#refreshCode").click(function() {
      var urlArray = window.location.href.split('/'),
          url = "";
      for(var i = 0; i < urlArray.length - 1; i++) {
        url += urlArray[i] + '/';
      }
      url += 'genCaptcha' + '?v=' + (new Date()).toString();
      $.get(url, function(data) {
        data = eval('(' + data + ')');
        $("#refreshCode").prev().attr("src", $(data.url).attr("src"));
      });
    });
  }

  if($("#loginbox").length > 0) {
    $("#loginbox").dialog({
      width : 420,
      autoOpen : false,
      modal : true,
      close: function(event, ui) {
        $("object").show();
      }
    });
  }
  
  if($("#pw_reset").length > 0) {
    $("#pw_reset").dialog({
      width : 420,
      autoOpen : false,
      modal : true,
      close: function(event, ui) {
        $("object").show();
      }
    });
  }

  $('.ttzcountdown').each(function() {
    var $this = $(this);
    setTimeout(function() {showtime($this)}, 10); 
  });
  
  $("#bodysignup").find(".forminput").eq(0).click(function() {
    var $this = $(this);
    if($this.val() == "电子邮箱地址") {
      $this.val("");
    }
  }).blur(function() {
    var $this = $(this);
    if($this.val() == "") {
      $this.val("电子邮箱地址");
    }
  });
  
  $(".addNewTag").click(function() {
    $("#pw_reset").dialog("open");
  });
  
  $("#forgot_password").click(function() {
    $("#loginbox").dialog("close");
    $("object").hide();
    $("#pw_reset").children("div").remove().end().dialog("open");
  });
  
  $("#pw_reset_button").click(function() {
    $("#pw_reset").dialog("close");
  });
  
  $(".signup-location").css("opacity", 0).change(function() {
    var $this = $(this);
    $this.prev().html($this.find("option:selected").text());
    if($this.attr("id") == "change-location") {
      window.location.href = $this.val();
    }
  });
  
  $("#thesidebar .boxtitle  a").click(function() {
    var $this = $(this),
        $t = $this.parent().next();
    if($t.css("display") == "none") {
      $t.show();
      $this.removeClass("closed");
    }
    else {
      $t.hide();
      $this.addClass("closed")
    }
  });
  
  $("#loginLink").click(function() {
    $("#loginbox-body").children("div").remove();
    $("object").hide();
    $("#loginbox").dialog("open");
  });
  
  $("#thesidebar .boxcontent h6 a").click(function() {
    $(this).parent().next().find("input").attr("checked", true);
  });
  
  $("#settings a.check_all").click(function() {
    $(this).parents("fieldset").eq(0).find(".settings-checkbox input").attr("checked", true);
  });
  
  onlyCheckOne("citySettings");
  onlyCheckOne("mailSettings");
  checkLogin();
  adminTag();
  getPWBack();
  
  $("#selectAllKinds").click(function() {
    $("#thesidebar").find("input[name='tags']").attr("checked", "checked");
    ajaxUpdateIndex();
  });
  
  $("#clearAllKinds").click(function() {
    $("#thesidebar").find("input[name='tags']").removeAttr("checked");
    ajaxUpdateIndex();
  });
  
  $("#selectAllSites").click(function() {
    $("#thesidebar").find("input[name='sites']").attr("checked", "checked");
    ajaxUpdateIndex();
  });
  
  $("#clearAllSites").click(function() {
    $("#thesidebar").find("input[name='sites']").removeAttr("checked");
    ajaxUpdateIndex();
  });
  
  $("#thesidebar").find("input[name='tags']").click(function() {
    ajaxUpdateIndex();
  });
  
  $("#thesidebar").find("input[name='sites']").click(function() {
    ajaxUpdateIndex();
  });
  
  $(".tag_item .only").unbind().click(function() {
    ajaxUpdateIndex("tagonly", $(this).prev().children("input"));
  });
  
  $(".site_item .only").unbind().click(function() {
    ajaxUpdateIndex("siteonly", $(this).prev().children("input"));
  });
  
  $(".tag_item .resultnumber a").unbind().click(function() {
    ajaxUpdateIndex("tagonly", $(this).parent().next().children("input"));
  });
  
  $(".site_item .resultnumber a").unbind().click(function() {
    ajaxUpdateIndex("siteonly", $(this).parent().next().children("input"));
  });
  
  $("#fbtime").click(function() {
    $("#sortoptions").children("li").removeClass("saon").removeClass("on").removeClass("sbon");
    $(this).addClass("saon on");
    if($("#sortoptions").hasClass("starttime_d")) {
      $("#sortoptions").attr("class", "").addClass('starttime_a');
      $(this).find("img").attr("src", "/code/img/sort-up.png");
    }
    else {
      $("#sortoptions").attr("class", "").addClass('starttime_d');
      $(this).find("img").attr("src", "/code/img/sort-down.png");
    }
    
    ajaxUpdateIndex();
  });
  
  $("#zhSort").click(function() {
    $("#sortoptions").children("li").removeClass("saon").removeClass("on").removeClass("sbon");
    $(this).addClass("on");
    $("#sortoptions").attr("class", "").addClass('total');
    
    ajaxUpdateIndex();
  });
  
  $("#pxprice").click(function() {
    $("#sortoptions").children("li").removeClass("saon").removeClass("on").removeClass("sbon");
    $(this).addClass("sbon on");
    if($("#sortoptions").hasClass("price_d")) {
      $("#sortoptions").attr("class", "").addClass('price_a');
      $(this).find("img").attr("src", "/code/img/sort-up.png");
    }
    else {
      $("#sortoptions").attr("class", "").addClass('price_d');
      $(this).find("img").attr("src", "/code/img/sort-down.png");
    }
    
    ajaxUpdateIndex();
  });
  
  $("#pxdiscount").click(function() {
    $("#sortoptions").children("li").removeClass("saon").removeClass("on").removeClass("sbon");
    $(this).addClass("sbon on");
    if($("#sortoptions").hasClass('salerate_d')) {
      $("#sortoptions").attr("class", "").addClass('salerate_a');
      $(this).find("img").attr("src", "/code/img/sort-up.png");
    }
    else {
      $("#sortoptions").attr("class", "").addClass('salerate_d');
      $(this).find("img").attr("src", "/code/img/sort-down.png");
    }
    
    ajaxUpdateIndex();
  });
  
  $("#pxlefttime").click(function() {
    $("#sortoptions").children("li").removeClass("saon").removeClass("on").removeClass("sbon");
    $(this).addClass("saon on");
    if($("#sortoptions").hasClass('closetime_d')) {
      $("#sortoptions").attr("class", "").addClass('closetime_a');
      $(this).find("img").attr("src", "/code/img/sort-up.png");
    }
    else {
      $("#sortoptions").attr("class", "").addClass('closetime_d');
      $(this).find("img").attr("src", "/code/img/sort-down.png");
    }
    
    ajaxUpdateIndex();
  });
})

function getPWBack() {
  var $btn = $("#getpwback");
  if($btn.length > 0) {
    var $email = $btn.prev(),
        $form = $btn.parent(),
        $w = $("#pw_reset");
    $form.attr("url", $form.attr("action"));
    $form.removeAttr("action");
    $btn.click(function() {
      $form.parent().children().not("form").remove();
      if($email.val() == "") {
        $form.before('<div style="color:red">邮箱不能为空</div>');
        return;
      }
      $.post($form.attr("url"), $form.serialize(), function(data) {
        var data = eval('(' + data + ')');
        if(data.ret) {
          $form.before('<div style="color:#8EB000">' + data.msg + '</div>');
          window.setTimeout(function() {window.location.reload()}, 3000);
        }
        else {
          $email.val('');
          data.msg = data.msg || '邮箱有误，请重新输入';
          $form.before('<div style="color:red">' + data.msg + '</div>');
        }
        return false;
      });
    });
  }
}

function showtime($obj){
  var now = new Date();
  var leftTime=parseInt($obj.attr("endtime"))-now.getTime();
  if(leftTime < 0) {
    $obj.html("已结束");
  }
  else {
    var leftsecond = parseInt(leftTime/1000);
    var day1=Math.floor(leftsecond/(60*60*24));
    var hour=Math.floor((leftsecond/3600));
    var minute=Math.floor(((leftsecond-hour*3600)/60));
    var second=Math.floor(leftsecond-hour*3600-minute*60);
    $obj.html(hour+"小时"+minute+"分"+second+"秒");
    setTimeout(function() {showtime($obj)}, 1000);
  }
}

// 'http://www.tuan.com/index.php/show/goods'
// 'http://www.tuan.com/index.php/show/goods/2/1/-/starttime_d/-/0/'
/*
  $city_id, 
  $is_active=true,
  $cat_lst = '-', 
  $order_type = 'starttime_d',
  $site_list = '-',
  $start_price = 0, 
  $end_price = -1,
  $start_discount = 0, 
  $end_discount = -1,
  $start_timeleft=0, 
  $end_timeleft=-1,
  $offset = 0
*/
function ajaxUpdateIndex(type, $obj) {
  var url = "",
      final_url = category_url;
  if(typeof category_url == "undefined") {
    return;
  }
  else {
    final_url = category_url;
    url = category_url.replace('goods', '');
  }
  
  var $tags = $("#thesidebar").find("input[name='tags']:checked"),
      $sites = $("#thesidebar").find("input[name='sites']:checked"),
      city_id = $("#change-location").val() ? $("#change-location").val().replace(url + 'city/', '') : "1",
      is_active = 'true',
      cat_lst = '',
      order_type = $("#sortoptions").attr("class"),
      site_list = '',
      offset = 0;
  if(type == "tagonly") {
    $tags.removeAttr("checked");
    $obj.attr("checked", "checked");
    $tags = $obj;
  }
  else if(type == "siteonly") {
    $sites.removeAttr("checked");
    $obj.attr("checked", "checked");
    $sites = $obj;
  }
  
  
  for(var i = 0; i < $tags.length; i++) {
    cat_lst += $tags.eq(i).val() + '-';
  }
  cat_lst = cat_lst.substring(0, cat_lst.length - 1);
  
  for(var i = 0; i < $sites.length; i++) {
    site_list += $sites.eq(i).val() + '-';
  }
  site_list = site_list.substring(0, site_list.length - 1);
  
  final_url += '/' + city_id + '/' + is_active + '/' + cat_lst + '/' + order_type + '/' + site_list + '/' + start_price + '/' + end_price + '/' + start_discount + '/' + end_discount + '/' + start_timeleft + '/' + end_timeleft + '/' + offset + '/';
  $.get(final_url, function(data) {
    data = eval('(' + data + ')');
    $("#dealCounts").html(data.count);
    var $prev = $("#dashboard-body").prev(),
        $html = $(data.html),
        $items = $html.children(".deal"),
        $s = $('<div id="dashboard-body"></div>');
        
    dealRenderCount = 0;
    $("#dashboard-body").remove();
    for(var i = dealRenderCount; i < ($items.length > dealRenderCount + 10 ? dealRenderCount + 10 : $items.length); i++) {
      $s.append($items.eq(i));
    }
    if($items.length > dealRenderCount + 10) {
      dealRenderCount += 10;
      window.getDealsInterval = setInterval(function() {
        if($(document).scrollTop() >= $(document).height() * 0.382) {  
          for(var i = dealRenderCount; i < ($items.length > dealRenderCount + 10 ? dealRenderCount + 10 : $items.length); i++) {
            $("#dashboard-body").children(".deal:last").after($items.eq(i));
          }
          if($items.length <= dealRenderCount + 10) {
            clearInterval(getDealsInterval);
          }
          else {
            dealRenderCount += 10;
          }
          $('.ttzcountdown').each(function() {
            var $this = $(this);
            setTimeout(function() {showtime($this)}, 500); 
          });
        }
      }, 200);
    }
    
    $prev.after($s);
    
    $('.ttzcountdown').each(function() {
      var $this = $(this);
      setTimeout(function() {showtime($this)}, 10); 
    });
    
    $("body").append('<script type="text/javascript" src="http://v1.jiathis.com/code/jia'+'.js"></sc'+'ript>');
  });
}

function onlyCheckOne(id) {
  var $checkboxes = $('#' + id).find("input:checkbox");
  $checkboxes.click(function() {
    var $this = $(this);
    if(!!$this.attr("checked")) {
      $checkboxes.each(function() {
        $(this).removeAttr("checked");
      });
    }
    $this.attr("checked", true);
  });
}

function checkLogin() {
  var $lb = $("#loginbox-body");
  if($lb.length > 0) {
    var $lbi = $("#loginButton"),
        $form = $lb.children("form").eq(0),
        $username = $("#login-email"),
        $pw = $("#login-pass");
    $form.attr("url", $form.attr("action"));
    $form.removeAttr("action");
    $username.keyup(function(event) {
      if (event.keyCode == '13') {
        $form.parent().children().not("form").remove();
        if($username.val() == "") {
          $form.before('<div style="color:red">用户名不能为空</div>');
          return;
        }
        if($pw.val() == "") {
          $form.before('<div style="color:red">密码不能为空</div>');
          return;
        }
        $.post($form.attr("url"), $form.serialize(), function(data) {
          var data = eval('(' + data + ')');
          if(data.ret) {
            window.location.reload();
          }
          else {
            $username.val('');
            $pw.val('');
            $form.before('<div style="color:red">用户名或密码错，请重新输入</div>');
          }
          return false;
        });
      }
    });
    $pw.keyup(function(event) {
      if (event.keyCode == '13') {
        $form.parent().children().not("form").remove();
        if($username.val() == "") {
          $form.before('<div style="color:red">用户名不能为空</div>');
          return;
        }
        if($pw.val() == "") {
          $form.before('<div style="color:red">密码不能为空</div>');
          return;
        }
        $.post($form.attr("url"), $form.serialize(), function(data) {
          var data = eval('(' + data + ')');
          if(data.ret) {
            window.location.reload();
          }
          else {
            $username.val('');
            $pw.val('');
            $form.before('<div style="color:red">用户名或密码错，请重新输入</div>');
          }
          return false;
        });
      }
    });
    $lbi.click(function() {
      $form.parent().children().not("form").remove();
      if($username.val() == "") {
        $form.before('<div style="color:red">用户名不能为空</div>');
        return;
      }
      if($pw.val() == "") {
        $form.before('<div style="color:red">密码不能为空</div>');
        return;
      }
      $.post($form.attr("url"), $form.serialize(), function(data) {
        var data = eval('(' + data + ')');
        if(data.ret) {
          window.location.reload();
        }
        else {
          $username.val('');
          $pw.val('');
          $form.before('<div style="color:red">用户名或密码错，请重新输入</div>');
        }
        return false;
      });
    });
  }
}

function adminTag() {
  var $ant = $(".addNewTag"),
      $at = $(".adminTag"),
      $ac = $(".adminCategory");
  if($ant.length == 0) {
    return;
  }
  
  for(var i = 0; i < $ac.length; i++){
    (function() {
      var $t = $ac.eq(i),
          $u = $at.eq(i);
      $.get(global_site_url + '/admin/childcat/' + $t.val(), function(data) {
        data = eval('(' + data + ')');
        $u.children().remove();
        for(var key in data) {
          $u.append('<option value="' + key + '">' + data[key] + '</option>');
        }
      });
      
      $t.change(function() {
        $.get(global_site_url + '/admin/childcat/' + $t.val(), function(data) {
          data = eval('(' + data + ')');
          $u.children().remove();
          for(var key in data) {
            $u.append('<option value="' + key + '">' + data[key] + '</option>');
          }

          $.get(global_site_url + '/admin/setcat/' + $t.parents(".deal").eq(0).attr("dealid") + '/' + $t.val() + '/' + $u.val() + '/', function(data) {});
        });
      });
      
      $u.change(function() {
        $.get(global_site_url + '/admin/setcat/' + $u.parents(".deal").eq(0).attr("dealid") + '/' + $t.val() + '/' + $u.val() + '/', function(data) {});
      });
    })();
  }
  
  $("#newTagDialog").dialog({
      width : 420,
      autoOpen : false,
      modal : true
    });
  $ant.click(function() {
    $("#newTagDialog").dialog("open");
  });
  
  $("#newTagDialog .formbutton").click(function() {
    if($.trim($("#newTagName").val()) == '') {
      return;
    }
    else {
      $.get(window.location.href.replace('#this', '').replace('/goods', '/addlev2cat/' + urlencode(urlencode($("#newTagName").val())) + '/' + $("#newTagDialog select").val()), function(data) {
        data = eval('(' + data + ')');
        $("#newTagName").parent().parent().before('<div style="color:#8EB000">添加成功</div>');
        window.setTimeout(function() {
          window.location.reload();
        }, 2000);
      });
    }
  });
}

function urlencode(s) {
  s = encodeURIComponent(s);
  return s.replace(/~/g,'%7E').replace(/%20/g,'+');
 }